<template>
  <div class="widget-container flex-box main" style="flex-wrap: wrap">
    <div class="box-area" v-for="(item, index) in imageSource" :key="index">
      <div
        class="flex-box dropzone-box dx-theme-border-color dropzone-image"
        v-if="item"
      >
        <!--  [".jpg", ".jpeg", ".gif", ".png"] -->
        <linkimg
          v-if="
            allowedFileExtensions.find((item) => {
              item == '.jpg' ||
                item == '.jpeg' ||
                item == '.gif' ||
                item == '.png';
            })
          "
          :src="item[srcProperty] || item"
          alt=""
          aaa="555"
        />
        <p
          v-else
          class="word3"
          style="
            padding: 0 10px;
            line-height: 30px;
            text-align: center;
            color: #666;
          "
        >
          上传完成 {{ item[srcProperty] || item }}
        </p>
      </div>
      <div class="remove" @click="onRemove(index)">
        <span class="dx-icon dx-icon-close"></span>
      </div>
    </div>

    <div
      v-if="!(limit === imageSource.length && limit !== 0) && !disabled"
      class="flex-box upload-box"
      :class="[
        isDropZoneActive
          ? 'dx-theme-accent-as-border-color dropzone-active'
          : 'dx-theme-border-color',
      ]"
    >
      <div class="flex-box dropzone-text">
        <span class="dx-icon dx-icon-add" v-if="!progressVisible"></span>
        <DxProgressBar
          id="upload-progress"
          :min="0"
          :max="100"
          width="30%"
          :show-status="false"
          :visible="progressVisible"
          :value="progressValue"
        />
      </div>
      <!-- :uploadHeaders="uploadHeaders" -->
      <!-- :upload-url="BASE_URL" -->
      <!-- @uploaded="onUploaded" -->
      <DxFileUploader
        id="file-uploader"
        :elementAttr="{ class: 'file-uploader' }"
        dialog-trigger="#dropzone-external"
        drop-zone="#dropzone-external"
        :multiple="multiple"
        :allowed-file-extensions="allowedFileExtensions"
        upload-mode="instantly"
        name="file"
        :visible="true"
        :uploadFile="uploadFile"
        @drop-zone-enter="onDropZoneEnter"
        @drop-zone-leave="onDropZoneLeave"
        @progress="onProgress"
        @upload-started="onUploadStarted"
        @upload-error="onUploadError"
      />
    </div>
  </div>
</template>
<script lang='ts'>
import { DxFileUploader } from "devextreme-vue/file-uploader";
import { DxProgressBar } from "devextreme-vue/progress-bar";
import { confirm } from "devextreme/ui/dialog";
import { prop } from "vue-class-component";
import { Options, Prop, Vue } from "vue-property-decorator/lib";
import config from "@/config/config";
import { get } from "js-cookie";
import notify from "devextreme/ui/notify";
import { Inject } from "vue-property-decorator";
import { ApiTool } from "@/api/api-tool";
import { CatalogClient } from "@/api/api_catalogclient";
// import { EnterpriseClient } from "@/api/api_enterpriseclient";
const BASE_URL = config.baseUrl + "/Api/Enterprise/UploadForEnterpriseTempFile";
let self: any;
@Options({
  components: {
    DxFileUploader,
    DxProgressBar,
  },
  props: {
    limit: {
      type: Number,
      default: 0,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    files: {
      type: [Array, String],
      required: true,
    },
    srcProperty: {
      type: String,
      default: "remoteFilePath",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    allowedFileExtensions: {
      type: Array,
      default: function () {
        return [".jpg", ".jpeg", ".gif", ".png"];
      },
    },
  },
  computed: {
    dataType: function () {
      return typeof this.files;
    },
  },
  ///change调用change 获取 image的值
  emits: ["change", "update:files"],
  watch: {
    files: {
      deep: true,
      handler(newVal, oldVal) {
        this.setValue(newVal);
      },
    },
  },
})
export default class ImageUpload extends Vue {
  srcProperty: string;
  uploadHeaders: any;
  BASE_URL = BASE_URL;
  isDropZoneActive = false;
  imageSource: (string | ArrayBuffer)[] = [];
  textVisible = true;
  progressVisible = false;
  progressValue = 0;
  allowedFileExtensions: Array<string>;
  files!: [];
  dataType!: string;
  onRemove(index) {
    let result = confirm("删除操作不可逆，确认删除图片吗?", "温馨提示");
    result.then((dialogResult) => {
      if (dialogResult) {
        if (index > -1) {
          this.imageSource.splice(index, 1);
        }
        let result = this.getValue(this.imageSource);
        this.$emit("change", result);
        this.$emit("update:files", result);
      }
    });
  }
  // 上传文件
  uploadFile(file, progressCallback) {
    let client = this.apiTool.createClient(CatalogClient);
    return client
      .uploadTempFile({
        data: file,
        fileName: "file",
      })
      .then((result) => {
        if (result.isSuccess == true) {
          this.onUploaded(result);
        } else {
          throw new Error("服务器异常.");
        }
      })
      .catch((error) => {
        throw new Error("服务器超时." + error);
      });
  }
  onDropZoneEnter(e) {
    if (e.dropZoneElement.id === "dropzone-external") {
      this.isDropZoneActive = true;
    }
  }
  onDropZoneLeave(e) {
    if (e.dropZoneElement.id === "dropzone-external") {
      this.isDropZoneActive = false;
    }
  }
  onUploadError(e) {
    this.progressVisible = false;
    this.progressValue = 0;
    notify("图片上传失败", "error", 2000);
  }
  // uploaded(res){
  //   this.onUploaded(res)
  // }
  onUploaded(res) {
    let img = this.srcProperty ? res.data : res.data.remoteFilePath;
    this.imageSource.splice(this.imageSource.length, 0, img);
    this.progressVisible = false;
    this.progressValue = 0;
    let result = this.getValue(this.imageSource);
    this.$emit("change", result);
    this.$emit("update:files", result);
  }
  onProgress(e) {
    this.progressValue = (e.bytesLoaded / e.bytesTotal) * 100;
  }
  onUploadStarted() {
    // this.imageSource = [];
    this.progressVisible = true;
  }
  // 获取emit数据
  getValue(value) {
    return this.dataType == "object" ? value : value.toString();
  }
  // 数据初始化
  setValue(value) {
    if (!value) {
      this.imageSource = [];
    } else if (typeof value == "string") {
      this.imageSource = value.split(",");
    } else {
      this.imageSource = value;
    }
  }
  @Inject()
  apiTool: ApiTool;
  mounted() {
    // let token = get("AccessToken.ClinicApi");
    // this.uploadHeaders = {
    //   Authorization: "Basic c2FiZXI6c2FiZXJfc2VjcmV0",
    //   "Blade-Auth": token,
    // };
    self = this as any;
    this.setValue(this.files);
  }
}
</script>
<style lang='scss' scoped>
.box-area {
  position: relative;
  > .remove {
    position: absolute;
    top: 0;
    width: 30px;
    height: 30px;
    right: 10px;
    color: #fff;
    background-color: rgba(0, 0, 0, 0.4);
    border-radius: 4px;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 10;
    > span {
      font-size: 20px;
    }
  }
}
.dropzone-box {
  width: 120px;
  height: 120px;
  background-color: rgba(183, 183, 183, 0.1);
  border-width: 1px;
  border-style: solid;
  border-radius: 4%;
  box-sizing: border-box;
  margin-right: 10px;
  margin-bottom: 10px;
  &.dropzone-active {
    border-style: solid;
  }
  &.dropzone-image {
    border-width: 0px;
    position: relative;
    z-index: 1;

    > img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      border-radius: 4%;
    }

    > * {
      pointer-events: none;
    }
  }
}

.widget-container {
  > span {
    font-size: 22px;
    font-weight: bold;
    margin-bottom: 16px;
  }
}

.dropzone-text {
  width: 120px;
  height: 120px;
  background-color: rgba(183, 183, 183, 0.1);
  border-color: rgba(183, 183, 183, 0.1);
  border-width: 1px;
  border-style: solid;
  border-radius: 4%;
  box-sizing: border-box;
  margin-bottom: 10px;
  > span {
    font-weight: 100;
    opacity: 0.5;
  }
}
#upload-progress {
  display: flex;
  margin-top: 10px;
}
.flex-box {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  flex-wrap: nowrap;

  &.main {
    justify-content: flex-start;
    flex-direction: row;
  }
}
.file-uploader {
  padding: 0;
  width: 140px;
  height: 140px;
  overflow: hidden;
  opacity: 0;
  position: absolute;
  z-index: 100;
  top: -20px;
  left: -10px;
  .dx-button-content {
    width: 120px;
    height: 120px;
  }
}
.upload-box {
  position: relative;
}
</style>
<style lang="scss">
.file-uploader {
  .dx-fileuploader-input-wrapper .dx-button {
    width: 140px;
    height: 120px;
  }
}
</style>

